<template>
  <div class="white-module search">
    <div class="troops">
      <img src="@/assets/title_bg.png" />
      <div class="c"><span>参赛代表队</span> {{ userInfo ? userInfo.team.teamName : '' }} <span>领队</span> {{ userInfo ?
        userInfo.leader.realName:''}}</div>
    </div>
    <el-row class="search-module">
      <el-col class="search-left" :span="21">
        <div class="item"> <span class="text">赛季</span><el-select v-model="dataForm.season" style="width:285px"
            placeholder="请选择">
            <el-option v-for="itemO in sessionList" :key="itemO.code" :label="itemO.name" :value="itemO.code">
            </el-option>
          </el-select></div>
        <div class="item">
          <span class="text">赛事层级</span><el-select style="width:285px" placeholder="请选择" v-model="dataForm.matchLevel">
            <el-option v-for="itemO in matchList" :key="itemO.code" :label="itemO.name" :value="itemO.code">
            </el-option>

          </el-select>
        </div>
        <div class="item">
          <span class="text">赛事地区</span>
          <el-select style="width:285px" placeholder="请选择" v-model="dataForm.province" @change="selectCity">
            <el-option value="" label="全国">全国</el-option>
            <el-option v-for="itemO in area.item" :key="itemO.code" :label="itemO.name" :value="itemO.code">
            </el-option>
          </el-select>
        </div>
        <div class="item">
          <span class="text">赛事城市</span>
          <el-select style="width:285px" placeholder="请选择" v-model="dataForm.city">
            <el-option value="" label="全部">全部</el-option>
            <el-option v-for="itemO in areaCity.item" :key="itemO.code" :label="itemO.name" :value="itemO.code">
            </el-option>
          </el-select>
        </div>
        <div>

          <span class="text">赛事时间</span>
          <el-date-picker v-model="dataForm.beginDate" type="date" placeholder="选择日期">
          </el-date-picker>
          <span style="padding:0px 2px 0px 10px">-</span>
          <el-date-picker v-model="dataForm.endDate" type="date" placeholder="选择日期">
          </el-date-picker>
        </div>
      </el-col>

      <el-col class="right-btn" :span="3">
        <el-button type="primary" @click="query">查询</el-button>
        <el-button type="default" @click="reset">重置</el-button>
      </el-col>
    </el-row>
  </div>
  <div class="total-input">
    <div class="input" style="margin-left: auto"><input placeholder="请输入关键字" v-model="dataForm.searchStr" /><img
        src="@/assets/common/search.png" @click="query" /></div>
  </div>
  <el-row class="global-pagination">
    <div class="total">共{{ total }}条数据</div>
    <!--    <el-col :span="8" class="total"> 共搜索 {{total}} 条数据 </el-col>-->
    <el-col :span="16">
      <el-pagination background layout="  prev, pager, next, jumper" :total="total" :page-size="10" :current-page="page"
        :small="false" :disabled="false" @size-change="query" @current-change="pageCurrentChangeHandle" />
    </el-col>
  </el-row>
  <div class="white-module st" v-for="(item, index) in dataList">
    <div class="contest-title">
      <div class="left">
        <span>{{ item.match_name }}</span>
        <span>比赛时间 {{ item.begindate }}</span>
        <span>报名时间 {{ item.signdate }}</span>
        <span>共{{ item.detail.length }}条</span>
      </div>
      <div class="right">
        <!--增加全部已读按钮-->
        <el-button type="text" style="margin-right: 150px;" @click="allRead" v-if="unreadFlag">全部已读</el-button>
        <strong>{{ item.seasonname }}</strong>
      </div>
    </div>
    <div class="global-table">
      <el-table :data="item.detail" :header-cell-style="{
        background: '#F5F7FA',
        color: '#333',
      }" style="width: 100%">
        <el-table-column prop="item_name" label="赛项" />
        <el-table-column prop="team_name" label="队伍名称" />
        <el-table-column prop="group_name" label="组别" />
        <el-table-column prop="real_name" label="选手">
          <template #default="scope">
            <block v-for="(rowItem, rowIndex) in splitName(scope.row.real_name, scope.row.ticket_url)">
              {{ rowIndex > 0 ? '、' : '' }}
              <a v-if="rowItem.pic" :href="rowItem.pic" style=" text-decoration: none;color: #00A0E9;"
                target="_blank">{{ rowItem.name }}</a>
              <span v-else>{{ rowItem.name }}</span>
            </block>
            <!--
                <a v-if="scope.row.ticket_url" :href="scope.row.ticket_url" style=" text-decoration: none;color: #00A0E9;" target="_blank">{{scope.row.real_name}}</a>
                <span v-else>{{scope.row.real_name}}</span>
                -->
          </template>
        </el-table-column>
        <el-table-column label="状态">
          <template #default="scope">
            <span class="yellow" v-if="scope.row.status == 0">审核中</span>
            <span class="green" v-if="scope.row.status == 1">报名成功</span>
            <span v-if="scope.row.status == 2">
              <!--晋级确认截止-->
              <span class="grey" v-if="scope.row.reject_reason == '晋级确认截止'">晋级确认截止</span>
              <span class="green" v-else-if="scope.row.is_rise === 1">已确认晋级</span>
              <!--已晋级-->
              <span class="green" v-else>完赛</span>
            </span>
            <span class="grey" v-if="scope.row.status == 3">未参赛</span>
            <span class="yellow" v-if="scope.row.status == 4">比赛中</span>
            <span v-if="scope.row.status == 5">
              <span class="grey" v-if="scope.row.reject_reason === '放弃晋级'">放弃晋级</span>
              <span class="yellow" v-else>已获晋级资格</span>
            </span>
            <!--2023.3.27号   完赛-> 晋级成功 -->
            <span class="green" v-if="scope.row.status == 6">晋级成功</span>
            <span class="red" v-if="scope.row.status == 7">弃权</span>
            <span class="red" style="cursor: pointer; " v-if="scope.row.status == 8"
              @click="scope.row.reject_reason ? showRejectReason(scope.row.reject_reason) : ''">驳回
              {{ scope.row.reject_reason ? '(查看原因)' : '' }}</span>
            <span class="yellow" v-if="scope.row.status == 9">待确认</span>
            <span class="grey" v-if="scope.row.status == 10">报名未成功</span>
          </template>


        </el-table-column>
        <el-table-column label="操作" width="280">
          <template #default="scope">
            <div v-if="scope.row.status == 10">
              <div style="color: #959ca9;">报名已截止</div>
            </div>
            <div v-else class="btns">
              <span @click="handleInfo(scope.row.id, scope.row.status)"> 查看信息 </span>
              <span v-if="scope.row.status == 5 && scope.row.reject_reason != '放弃晋级'"
                @click="cancel(scope.row.id, scope.row.status)"> {{ '放弃晋级' }} </span>
              <!--
                  <span type="text"  size="small"> 查看成绩 </span>
                  <span type="text"  size="small"> 获奖证书 </span>
                  -->
              <span @click="risehandle(scope.row.id, scope.row.status)"
                v-if="scope.row.status == 5 && scope.row.reject_reason != '放弃晋级'" type="text" size="small"> 申请晋级 </span>
              <span @click="confirmhandle(scope.row.id, item.match_level, scope.row.typename)"
                v-if="scope.row.status == 9" type="text" size="small"> 确认晋级 </span>
              <span
                v-if="scope.row.status == 0 || scope.row.status == 1 || scope.row.status == 4 || scope.row.status == 8 || scope.row.status == 9"
                @click="cancel(scope.row.id, scope.row.status)"> {{ scope.row.status == 0 || scope.row.status == 8 ? '取消报名' :
                '弃权'}} </span>
              <span
                @click="noticehandle(scope.row.match_item_id); saveItemNoticeLog(scope.row.match_item_id, scope.row.id);"
                v-if="scope.row.notice_title" type="text" size="small">
                赛项通知
                <span class="unread-dot" v-if="scope.row.readCount == 0"></span>
              </span>
              <!--基础赛项开启了抽签功能、-->
              <span @click="showDrawDialog(scope.row.id)"
                v-if="scope.row.is_draw == 1 && scope.row.draw_open == 1 && scope.row.sort == 0" type="text" size="small">
                开始抽签 </span>
              <span @click="showDrawResult(scope.row.sort)"
                v-if="scope.row.is_draw == 1 && scope.row.draw_open == 1 && scope.row.sort > 0" type="text" size="small"> 抽签结果
              </span>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
  <el-dialog v-model="dialogVisible" custom-class="global-hint-dialog" :show-close="false" width="400px">
    <div class="confirm-dialog">
      <div class="image"><img src="@/assets/common/hint_blue.png" /></div>
      <div class="text">本赛事报名已经截止，不可修改报名信息！</div>
      <div class="btns">
        <el-button type="primary" @click="dialogVisible = false">知道了</el-button>

      </div>
    </div>
  </el-dialog>

  <!--抽签弹窗-->
  <el-dialog v-model="drawVisible" :show-close="false" width="400px">
    <div class="confirm-dialog">
      <div class="image"></div>
      <div class="text">
        <!--动态显示随机数-->
        <div v-if="drawForm.drawNum == '0'">
          <!--<span style="color: #4cd964;font-size: 16px;font-weight: bold;" v-if="drawForm.randomNo>0">{{drawForm.randomNo}}</span>-->
          <span v-if="drawForm.randomNo != 0">正在抽签中，请点击确认抽出签号！</span>
          <span v-else>请点击确认，抽出签号</span>
        </div>
        <div v-else>抽签结果：<span style="color: #4cd964;font-size: 16px;font-weight: bold;">{{ drawForm.drawNum }}</span>
        </div>
      </div>
      <div class="btns">
        <el-button @click="drawVisible = false">关闭</el-button>
        <el-button type="primary" @click="drawhandle()"
          v-if="drawForm.drawNum == '0' && drawForm.btnShowFlag">确认</el-button>
      </div>
    </div>
  </el-dialog>

  <!--抽签结果-->
  <el-dialog v-model="drawResultVisible" :show-close="false" width="400px">
    <div class="confirm-dialog">
      <div class="image"></div>
      <div class="text">
        <!--动态显示随机数-->
        <div>抽签结果：<span style="color: #4cd964;font-size: 16px;font-weight: bold;">{{ drawForm.drawNum }}</span></div>
      </div>
      <div class="btns">
        <el-button @click="drawResultVisible = false">关闭</el-button>
      </div>
    </div>
  </el-dialog>

  <!--驳回原因-->
  <el-dialog v-model="rejectReasonVisible" :show-close="false" width="400px">
    <div class="confirm-dialog">
      <div class="image"></div>
      <div class="text">
        <!--动态显示随机数-->
        <div><span style="color: red;font-size: 16px;font-weight: bold;">{{ rejectReason }}</span></div>
      </div>
      <div class="btns">
        <el-button @click="rejectReasonVisible = false">关闭</el-button>
      </div>
    </div>
  </el-dialog>

</template>
<script lang="ts">
import { defineComponent, reactive, ref, toRefs } from "vue";
import listService from "@/utils/listService";
import router from "@/router";
import baseService from "@/utils/baseService";
import { ElMessage, ElMessageBox } from "element-plus";
import { getCache } from "@/utils/cache";

export default defineComponent({
  setup() {
    const state = reactive({
      getDataListURL: "/front/fast/match/matchRecord/page?pageSize=10",
      getDataListIsPage: true,
      deleteURL: "/pay/order",
      deleteIsBatch: true,
      dataForm: {
        city: '',
        season: '',
        matchLevel: '',
        province: '',
        beginDate: '',
        endDate: '',
        searchStr: '',
        noHistory: '1'
      },
      rejectReason: ''
    });
    return { ...listService(state), ...toRefs(state) };
  },

  data() {
    return {
      dataList: [{}, {}, {}, {}],
      sessionList: [{ name: "2023", code: "2023" }, { name: "2024", code: "2024" }, { name: "2025", code: "2025" }],
      matchList: [{ name: "国赛", code: "1" }, { name: "省赛", code: "2" }, { name: "市赛", code: "3" }],
      matchArea: [{ name: "上海", code: "1" }, { name: "青岛", code: "2" }, { name: "济南", code: "3" }],
      areaCity: { code: '0', item: [] },
      area: { code: '0', item: [] },
      dates: null,
      dates1: null,
      dialogVisible: false,
      drawVisible: false,
      drawResultVisible: false,
      rejectReasonVisible: false,
      isCollapse: 1,
      isNavCollapse: false,
      showDialogFlag: false,
      evaluationDialogFlag: false,
      updateForm: {
        id: null,
        schoolName: '',
        evaluation: ''
      },
      drawForm: {
        id: null,
        drawNum: '0',
        randomNo: 0,
        btnShowFlag: true
      },
      tableData: [
        {
          title: "个人飞行赛",
          name: "潍坊一中格斗1队",
          group: "初中组",
          user: "张三",
          state: 1,
        },
        {
          title: "个人飞行赛",
          name: "潍坊一中格斗1队",
          group: "初中组",
          user: "李典",
          state: 2,
        },
        {
          title: "个人飞行赛",
          name: "潍坊一中格斗1队",
          group: "初中组",
          user: "王小三",
          state: 3,
        },
        {
          title: "个人飞行赛",
          name: "潍坊一中格斗1队",
          group: "初中组",
          user: "王小三",
          state: 4,
        },
      ],
      formLabelWidth: '120px',
      userInfo: "",
      timer: 0,
      //是否有未读消息
      unreadFlag: false
    };
  },
  mounted() {
    baseService.areaList(this.area);
    this.userInfo = getCache('userInfo', { isSessionStorage: true }, {});
    //延迟5秒执行
    setTimeout(() => {
      this.checkUnread();
    }, 5000);
  },

  methods: {
    selectCity() {
      if (this.dataForm.province) {
        this.areaCity.code = this.dataForm.province;
        baseService.areaList(this.areaCity);
      } else {
        this.areaCity.item = [];
      }

    },
    handleInfo(id: any, status: number) {
      //router.push("/enroll/enrollInfo?id="+id);
      let typename = 'detail';
      //完赛
      if (status == 2) {
        typename = 'detail';
      } else {
        typename = 'edit';
      }
      router.push("/enroll/enrollInfo-detail?id=" + id + "&status=" + status + "&typename=" + typename);
      //判断跳转到省赛

      //判断跳转到国赛
    },
    cancel(id: any, status: number) {
      let msg = status == 1 ? "确认弃权？" : "确认取消报名？ 如需更新报名信息，请勿取消报名，请先在<a style='color: #00A0E9' >查看信息</a>中修改 ";
      let msg2 = status == 1 ? "弃权成功！" : "取消报名成功！";
      if (status == 5) {
        msg = "确认放弃晋级？";
        msg2 = "放弃晋级成功！";
      }
      ElMessageBox.confirm(msg, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        dangerouslyUseHTMLString: true
      }).then(e => {

        baseService.post("/front/spmatchItemTeam/cancel", { id: id }).then((e: any) => {


          if (e.code == 0) {
            ElMessage.success(msg2);
          } else {
            ElMessage.error(e.msg);
          }

          this.query();
        });
      });

    }
    , handlePromotion() {
      router.push("/enroll/promotion");
    }, reset: function () {
      if (this.dataForm) {
        this.dataForm = {
          season: '',
          matchLevel: '',
          city: '',
          province: '',
          beginDate: '',
          endDate: '',
          searchStr: '',
          noHistory: '1'
        };

      }
    },
    /**
     * 申请晋级
     * @param id
     */
    risehandle(id: any, status: number) {
      //router.push("/enroll/enrollInfo?id=" + id + "&type=rise");
      router.push("/enroll/enrollInfo-detail?id=" + id + "&status=" + status + "&typename=edit");
    },
    /**
     * 确认晋级
     * @param id
     */
    confirmhandle(id: any, match_levl: string, typename: string) {
      router.push("/enroll/confirmEnrollInfo?id=" + id + "&type=rise");
    },
    /**
     * 赛项通知
     */
    noticehandle(id: any) {
      router.push({ path: "/notice/detail2", query: { id: id } });
    },

    /**
     * 弹出抽签
     */
    showDrawDialog(id: any) {
      this.drawForm.drawNum = '0';
      this.drawForm.randomNo = 0;
      this.drawForm.btnShowFlag = true;
      this.drawVisible = true;
      this.drawForm.id = id;
      //随机滚动
      this.randomNum();
    },

    /**
     * 抽签
     * @param id
     */
    drawhandle() {
      //清除定时器
      clearInterval(this.timer);
      //抽签号码重置-1 不展示出来
      this.drawForm.randomNo = -1;
      //隐藏确定按钮
      this.drawForm.btnShowFlag = false;
      //倒计时执行3s
      setTimeout(() => {
        baseService.get("/front/spmatchItemTeam/draw?id=" + this.drawForm.id).then((res: any) => {
          if (res.code == 0) {
            this.drawForm.drawNum = res.data;
            ElMessage.success('抽签成功');
            this.query();
          } else {
            ElMessage.error(res.msg);
          }
        })
      }, 3000);
    },

    /**
     * 按照顿号分割用户名
     */
    splitName(userName: string, entryPic: string) {
      if (!userName) return [];
      let names = userName.split("、");
      let pics = entryPic ? entryPic.split("、") : [];
      let arr = [];
      for (let i = 0; i < names.length; i++) {
        arr.push({ name: names[i], pic: pics[i] });
      }
      return arr;

      let str = "";
      for (let i = 0; i < names.length; i++) {
        if (pics[i]) {
          str += '<a href=' + pics[i] + '>' + names[i] + '</a> 、';
        } else {
          str += names[i] + "、";
        }
      }
      return str;
    },
    //随机数跳动
    randomNum() {
      //定时器
      this.timer = setInterval(() => {
        let num = Math.floor(Math.random() * 200);
        this.drawForm.randomNo = num;
      }, 100);
    },
    //查看抽签结果
    showDrawResult(drawNum: any) {
      this.drawResultVisible = true;
      this.drawForm.drawNum = drawNum;
    },

    //保存日志 saveItemNoticeLog
    saveItemNoticeLog(matchItemId: any, userId: any) {
      baseService.get("/front/notice/saveItemNoticeLog", {
        matchItemId: matchItemId,
        userId: userId
      }).then((e: any) => {
        if (e.code == '0') {
          console.log("保存日志成功");
        }
      });
    },

    //弹出原因
    showRejectReason(reason: any) {
      this.rejectReason = reason;
      this.rejectReasonVisible = true;
    },

    /**
     * 查看是否有未读消息
     */
    checkUnread() {
      // 循环dataList,判断readCount=0表示有未读消息
      this.dataList.forEach((item: any) => {
        //再次循环item里的detail
        item.detail.forEach((item1: any) => {
          console.log('--------------', item.readCount)
          if (item1.readCount === '0') {
            this.unreadFlag = true;
          }
        });
      });
    },

    /**
     * 全部已读
     */
    allRead() {
      // 把上面的内容改为for循环
      for (let i = 0; i < this.dataList.length; i++) {
        for (let j = 0; j < this.dataList[i].detail.length; j++) {
          if (this.dataList[i].detail[j].readCount === '0') {
            this.saveItemNoticeLog(this.dataList[i].detail[j].match_item_id, this.dataList[i].detail[j].id);
          }
        }
      }
      // 重新加载列表
      this.query();
      // 全部已读后，把未读消息标识改为false
      this.unreadFlag = false;
    }



  }
});
</script>
<style lang="scss" scoped>
.unread-dot {
  display: inline-block;
  /* 将 span 元素设置为块级元素 */
  width: 8px;
  /* 确定红点大小 */
  height: 8px;
  background-color: red;
  /* 设置背景颜色 */
  border-radius: 50%;
  /* 将红点设置为圆形 */
  margin-left: -3px;
  /* 如果和文字在一行上，需要设置左侧间距 */
  margin-top: -15px;
  vertical-align: middle;
  /* 设置垂直对齐方式为中间对齐 */
}

.search {
  padding: 20px 20px 5px;

  .troops {
    position: relative;
    margin: 0px 0px 25px 0px;

    img {
      width: 579px;
    }

    .c {
      position: absolute;
      left: 0px;
      top: 0px;
      width: 532px;
      line-height: 54px;
      border-radius: 6px;



      span {
        font-size: 16px;
        font-weight: $font-weight-bold;
        margin-left: 24px;
        margin-right: 11px
      }

      ;

      span:nth-child(2) {
        margin-left: 40px;
      }
    }
  }

  .search-module {
    margin-bottom: 14px;

    .search-left {
      display: flex;
      flex-wrap: wrap;



      .el-select {}
    }


  }
}

.total-input {
  padding: 16px 0px;
  display: flex;
  align-items: center;
  justify-content: space-between;

  .total {
    color: #959CA9;
  }

  .input {
    display: flex;
    align-items: center;
    justify-content: space-between;
    height: 32px;
    background: #FFFFFF;
    border-radius: 4px;
    width: 270px;
    padding-right: 12px;

    input {
      background: none;
      outline: none;
      border: 0px;
      flex: 1;
      padding-left: 15px;
    }

    @include input-placeholder(#959CA9);

    img {
      width: 16px;
      height: 16px;
      margin-left: 20px;
      cursor: pointer;

    }
  }
}

.st {
  padding: 20px;



  .contest-title {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 12px;

    .left {
      display: flex;
      align-items: center;
      font-weight: $font-weight-bold;

      span {
        margin-right: 30px;
      }

      span:first-child {
        color: $color-primary;
      }
    }

  }

  .global-table {
    margin-bottom: 34px;

    span.red {
      color: #FC5260;
    }

    span.red1 {
      color: red;
    }

    span.blue {
      color: #00B7B3;
    }

    span.green {
      color: forestgreen;
    }

    span.black {
      color: #4F5A70;
    }

    span.yellow {
      color: #FF8F3C;
    }

    span.grey {
      color: #959ca9;
    }

    .btns {
      display: flex;
      flex-wrap: wrap;
      color: $color-primary;
      margin: 1px 16px 1px 0px;
      line-height: normal;

      span {
        color: $color-primary;
        margin: 1px 16px 1px 0px;
        cursor: pointer;
      }
    }
  }
}
</style>
